<template>
  <div class="app-container">
    <help :show-help="showHelp" />
    <div class="filter-container">
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        style="width: 120px"
        clearable
        class="filter-item"
        @change="handleFilter"
        @clear="clearStatus"
      >
        <el-option
          v-for="item in statusMap"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.level"
        placeholder="等级"
        clearable
        class="filter-item"
        @change="handleFilter"
        style="margin-left: 10px"
        filterable
      >
        <el-option
          v-for="item in levelList"
          :key="item.id"
          :label="item.display"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-if="false"
        v-model="listQuery.new_level"
        placeholder="新等级"
        clearable
        class="filter-item"
        @change="handleFilter"
        style="margin-left: 10px"
        filterable
      >
        <el-option
          v-for="item in newLevel"
          :key="item.id"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
    </div>
    <div class="filter-container">
      <el-input
        v-model="listQuery.id"
        placeholder="ID"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.mobile"
        placeholder="手机"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.nickname"
        placeholder="昵称"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.referrer_id"
        placeholder="推荐人ID"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-button
        v-waves
        type="primary"
        icon="el-icon-search"
        class="filter-item"
        style="margin-left: 10px;"
        @click="handleFilter"
      >搜 索</el-button>
      <el-button
        v-waves
        type="success"
        icon="el-icon-refresh"
        class="filter-item"
        style="margin-left: 10px;"
        @click="clearFilter"
      >清除筛选</el-button>
    </div>
    <div class="filter-container">
      <el-button
        v-waves
        type="primary"
        icon="el-icon-circle-plus-outline"
        class="filter-item"
        size="small"
        @click="handleCreate"
      >添加会员</el-button>
      <el-button
        v-waves
        type="success"
        icon="el-icon-download"
        class="filter-item"
        size="small"
        plain
        :loading="listLoading"
        @click="handleExport"
      >导出 Excel</el-button>
      <el-button
        v-waves
        type="success"
        class="filter-item"
        size="small"
        plain
        @click="showHelp = !showHelp"
      >{{ showHelp ? '关闭帮助' : '显示帮助' }}</el-button>
    </div>
    <div class="filter-container">
      <el-checkbox
        v-model="listShow.id"
        class="filter-item"
      >
        显示ID
      </el-checkbox>
      <el-checkbox
        v-model="listShow.image"
        class="filter-item"
      >
        显示图片
      </el-checkbox>
      <el-checkbox
        v-model="listShow.date"
        class="filter-item"
      >
        显示日期
      </el-checkbox>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :border="false"
      fit
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column v-if="listShow.id" sortable="custom" prop="id" label="ID" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" width="120" v-if="listShow.image">
        <template slot-scope="{row}">
          <div class="demo-image__lazy">
            <el-image :src="row.avatar" lazy :fit="'cover'" :preview-src-list="[row.avatar]">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="手机" width="120">
        <template slot-scope="{row: { mobileWrapper }}">
          <span v-html="mobileWrapper" />
        </template>
      </el-table-column>
      <el-table-column label="昵称">
        <template slot-scope="{row}" v-if="row.nickname">
          <span v-html="row.nicknameWrapper" />
        </template>
      </el-table-column>
      <el-table-column label="性别" v-if="false">
        <template slot-scope="{row}">
          <span>{{ row.sex | sexText }}</span>
        </template>
      </el-table-column>
      <el-table-column label="等级" width="150">
        <template slot-scope="{row}" v-if="row.level0">
<!--          <span>{{ row.level0.display }} | <span v-if="row.level2 && +row.level2.value > 0">{{row.level2.name}}</span></span>-->
          <span>{{ row.level0.display }}</span>
        </template>
      </el-table-column>
      <el-table-column label="推荐人">
        <template slot-scope="{row}" v-if="row.referrer">
          <span>{{ row.referrer.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="帐户" align="left" width="200">
        <template slot-scope="{row}" v-if="row.account">
          <ul v-html="getAccountText(row.account)" class="account" />
        </template>
      </el-table-column>
      <el-table-column label="佣金" align="left" width="200">
        <template slot-scope="{row}" v-if="row.account">
          <ul v-html="getCommssionText(row.account)" class="account" />
        </template>
      </el-table-column>
      <el-table-column label="个人业绩" align="left" width="200">
        <template slot-scope="{row}">
          <ul class="account" v-html="getMy(row)"></ul>
        </template>
      </el-table-column>
      <el-table-column label="团队业绩" align="left" width="200">
        <template slot-scope="{row}">
          <ul class="account" v-html="getTeam(row)"></ul>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="status" label="状态" width="80">
        <template slot-scope="{row}">
          <span>
            <el-switch v-model="row.statusForm" @change="handleStatus(row)" />
          </span>
        </template>
      </el-table-column>
      <el-table-column v-if="listShow.date" label="注册时间" sortable="custom" prop="create_time" width="160">
        <template slot-scope="{row:{create_time}}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ create_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="220"
        fixed="right"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
            删除
          </el-button>
          <el-divider></el-divider>
          <el-button type="success" size="mini" icon="el-icon-delete" @click="handleTeam(row)">
            团队
          </el-button>
          <el-button type="success" size="mini" icon="el-icon-delete" @click="handleRefill(row)">
            充值
          </el-button>
          <el-divider></el-divider>
          <el-button type="primary" size="mini" @click="$router.push('/order?user_id=' + row.id)">
            我的订单
          </el-button>
          <el-button type="primary" size="mini" @click="handlePassword(row)">
            重置支付密码
          </el-button>
          <el-divider />
          <el-button type="success" size="mini" @click="$router.push('/member/commission/' + row.id)">
            收入
          </el-button>
          <el-button type="primary" size="mini" @click="$router.push('/member/consume/' + row.id)">
            消费
          </el-button>
          <el-button type="danger" size="mini" @click="$router.push('/finance/cash?user_id=' + row.id)">
            提现
          </el-button>
          <el-divider />
          <el-button v-if="+row.level === 301" type="danger" size="mini" @click="handleAreaArea(row)">
            指定区代
          </el-button>
          <el-button v-if="+row.level === 302" type="primary" size="mini" @click="handleAreaCity(row)">
            指定市代
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      @pagination="refresh"
    />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import api from '@/api'
import Help from './components/Help'
import config from '@/config'

const initQuery = {
  status: config.member.OPEN,
  page: 1,
  pageSize: 10,
  total: 0,
  sort: '+id'
}

export default {
  name: 'MemberList',
  components: {
    Pagination,
    Help
  },
  directives: { waves },
  filters: {
    timeFilter(time) {
      return time ? parseTime(time, '{m}-{d} {h}:{i}') : ''
    },
    statusText(status) {
      return config.member.statusText(+status)
    },
    sexText(v) {
      let text = ''
      if (+v === 1) {
        text = '男'
      }
      if (+v === 2) {
        text = '女'
      }
      return text
    }
  },
  data() {
    return {
      // 状态
      status: {},
      // 状态
      statusMap: [],
      // 显示帮助提示
      showHelp: false,
      listLoading: false,
      list: [],
      listQuery: {},
      defaultSort: {},
      selectionList: [],
      // 显示控制
      listShow: {
        id: true,
        date: true,
        image: true
      },
      // 等级
      levelList: [],
      newLevel: [
        { id: 1, name: '会员', value: 501 },
        { id: 2, name: '市场经理', value: 502 },
        { id: 3, name: '事业部', value: 503 },
        { id: 4, name: '分公司', value: 504 }
      ]
    }
  },
  created() {
    this.parseQuery()
  },
  mounted() {
    this.getStatusList()
    this.getList()
    this.getLevelList()
  },
  methods: {
    handlePassword(row) {
      this.$confirm('您确定要重置密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.member.resetPassword({ id: row.id }).then(response => {
          this.$message({
            message: '重置密码成功, 新密码为: 123456',
            type: 'success',
            duration: 3000
          })
        })
      }).catch(() => {})
    },
    handleAreaCity(item) {
      this.$router.push({
        path: `/member/city/${item.id}`
      })
    },
    handleAreaArea(item) {
      this.$router.push({
        path: `/member/area/${item.id}`
      })
    },
    getMy(v) {
      let a = `<li>金额: <span class="amount" style="color: red"> ￥${+v.my}</span></li>`
      a += `<li class="order">订单: <span style="color: blue">${+v.my_order}单</span></li>`
      return a
    },
    getTeam(v) {
      let a = `<li>金额: <span class="amount" style="color: red"> ￥${+v.team}</span></li>`
      a += `<li class="order">订单: <span style="color: blue">${+v.team_order}单</span></li>`
      return a
    },
    getCommssionText(v) {
      let a = `<li>已返:${+v.done_balance}</li>`
      a += `<li>待返:${+v.await_balance}</li>`
      return a
    },
    getAccountText(v) {
      let a = `<li>余额:${+v.balance}</li>`
      a += `<li>积分:${+v.score}</li>`
      // a += `<li>购物券:${+v.ticket}</li>`
      a += `<!--<li>优惠劵:${+v.platform_ticket}</li>-->`
      // a += `<li>临时积分:${+v.tmp_score}</li>`
      return a
    },
    /**
     * 清除状态
     */
    clearStatus() {
      // this.listQuery.status = config.member.ALL
      this.listQuery.status = null
    },
    getLevelList() {
      this.listLoading = true
      api.member.levelList().then(response => {
        const { data } = response
        this.levelList = data
        this.listLoading = false
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 获取状态列表
     */
    getStatusList() {
      this.listLoading = true
      api.member.statusList().then(response => {
        const { data } = response
        this.statusMap = data
        this.listLoading = false
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 获取数据列表
     */
    getList() {
      this.listLoading = true
      // 状态需要处理
      if (this.listQuery.status === '') {
        this.listQuery.status = initQuery.status
      }
      api.member.list({ ...this.listQuery }).then(response => {
        const { data } = response
        this.list = data.list
        this.listQuery.total = +data.totalCount
        this.listLoading = false
        this.list.forEach(x => {
          // 搜索高亮
          x.mobileWrapper = this.wrapperKeyword('mobile', x.mobile)
          x.nicknameWrapper = this.wrapperKeyword('nickname', x.nickname)
          // 状态处理
          const statusForm = +x.status === this.status.OPEN
          this.$set(x, 'statusForm', statusForm)
        })
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 新建
     */
    handleCreate() {
      this.$router.push({
        path: '/member/create'
      })
    },
    /**
     * 修改
     * @param row
     */
    handleUpdate(row) {
      this.$router.push({
        path: `/member/edit/${row.id}`
      })
    },
    /**
     * 删除
     * @param row
     */
    handleDelete(row) {
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.member.remove({ id: row.id }).then(response => {
          this.$message({
            message: response.message || '删除成功',
            type: 'success'
          })
          this.list.forEach(x => {
            if (x.id === row.id) {
              x.status = this.status.DELETE
            }
          })
          // 删除掉
          this.list = this.list.filter(x => +x.status !== this.status.DELETE)
          // this.handleFilter()
        })
      }).catch(() => {})
    },
    /**
     * 团队树
     */
    handleTeam(row) {
      this.$router.push(`/member/team/${row.id}`)
    },
    /**
     * 充值
     */
    handleRefill(row) {
      this.$router.push(`/member/refill/${row.id}`)
    },
    /**
     * 排序
     * @param data
     */
    sortChange(data) {
      const sortBy = (prop, order) => {
        if (prop && order === 'ascending') {
          this.listQuery.sort = `+${prop}`
        } else if (prop && order === 'descending') {
          this.listQuery.sort = `-${prop}`
        } else {
          this.listQuery.sort = ''
        }
      }
      const { prop, order } = data
      sortBy(prop, order)
      this.handleFilter()
    },
    /**
     * 刷新
     */
    refresh() {
      this.$router.push({
        path: '/member/list',
        query: this.listQuery
      })
    },
    /**
     * 过滤(筛选)
     */
    handleFilter() {
      // this.listQuery.page = 1
      this.refresh()
    },
    /**
     * 清除筛选
     */
    clearFilter() {
      this.listQuery = Object.assign({}, initQuery)
      this.defaultSort = {}
      this.refresh()
    },
    /**
     * 处理筛选条件
     */
    parseQuery() {
      const query = Object.assign({}, this.$route.query)
      let sort = '-id'
      this.listQuery = Object.assign({}, { ...initQuery, sort })
      if (Object.keys(query).length > 0) {
        // 注意这里的类型转换
        query.page && (query.page = +query.page)
        query.pageSize && (query.pageSize = +query.pageSize)
        query.total && (query.total = +query.total)
        query.status && (query.status = +query.status)
        query.sort && (sort = query.sort)
      }
      const sortSymbol = sort[0]
      const sortColumn = sort.slice(1, sort.length)
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol === '+' ? 'ascending' : 'descending'
      }
      this.listQuery = { ...this.listQuery, ...query }
      this.status = config.brand
    },
    /**
     * 查询高亮
     */
    wrapperKeyword(k, v) {
      const highlight = value => {
        return `<span style="color: #1890ff">${value}</span>`
      }
      if (!this.listQuery[k]) {
        return v
      }
      return v.replace(new RegExp(this.listQuery[k], 'ig'), v => highlight(v))
    },
    /**
     * 导出
     */
    // async handleExport() {
    //   const formatJson = (filterVal, jsonData) => {
    //     return jsonData.map(v => filterVal.map(j => {
    //       if (j === 'status') {
    //         return this.$options.filters['statusText'](v[j])
    //       }
    //       if (j === 'sex') {
    //         return this.$options.filters['sexText'](v[j])
    //       }
    //       if (j === 'level' && v['level0']) {
    //         return v['level0']['display']
    //       }
    //       return v[j]
    //     }))
    //   }
    //   this.listLoading = true
    //   if (this.listQuery.status === '') {
    //     this.listQuery.status = initQuery.status
    //   }
    //   const response = await api.member.list({ ...this.listQuery, export: true })
    //   import('@/vendor/Export2Excel').then(excel => {
    //     const tHeader = ['ID', '手机', '等级', '状态', '注册时间', '登录ip', '昵称', '头像', '推荐人ID', '性别']
    //     const filterVal = ['id', 'mobile', 'level', 'status', 'create_time', 'login_ip', 'nickname', 'avatar', 'referrer_id', 'sex']
    //     const list = response.data
    //     const data = formatJson(filterVal, list)
    //     excel.export_json_to_excel({
    //       header: tHeader,
    //       data,
    //       filename: '会员列表'
    //     })
    //   })
    //   this.listLoading = false
    // },
    async handleExport() {
      const formatJson = (filterVal, jsonData) => {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'status') {
            return this.$options.filters['statusText'](v[j])
          }
          if (j === 'level' && v['level0']) {
            return v['level0']['display']
          }
          if (j === 'balance') {
            return v['account'] ? v['account']['balance'] : ''
          }
          if (j === 'commission') {
            return v['account'] ? `已返: ${v['account']['done_balance']}, 待返: ${v['account']['await_balance']}` : ''
          }
          if (j === 'my') {
            return `金额: ￥${+v[j]}, 订单: ${v['my_order']}`
          }
          if (j === 'team') {
            return `金额: ￥${+v[j]}, 订单: ${v['team_order']}`
          }
          if (j === 'team_count') {
            return `${v['team_count']}人`
          }
          return v[j]
        }))
      }
      this.listLoading = true
      if (this.listQuery.status === '') {
        this.listQuery.status = initQuery.status
      }
      const response = await api.member.list({ ...this.listQuery, export: true })
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '手机', '等级', '状态', '注册时间', '登录ip', '昵称', '头像', '推荐人ID',
          '余额', '佣金', '个人业绩', '团队业绩', '团队总人数'
        ]
        const filterVal = ['id', 'mobile', 'level', 'status', 'create_time', 'login_ip', 'nickname', 'avatar', 'referrer_id',
          'balance', 'commission', 'my', 'team', 'team_count'
        ]
        const list = response.data
        const data = formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '会员列表'
        })
      })
      this.listLoading = false
    },
    /**
     * 状态设置
     */
    handleStatus(row) {
      const status = +row.statusForm
      api.member.changeStatus({ ...row, status }).then(response => {
        this.$notify({
          title: '成功',
          message: response.message || '设置成功',
          type: 'success',
          duration: 2000
        })
        // this.handleFilter()
        row.status = status
      })
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getList()
      }
    }
    next()
  }
}
</script>

<style scoped lang="scss">
.el-divider--horizontal {
  margin: 7.5px 0;
}
.account {
  text-align: left;
  list-style: none;
  padding: 0;
  li {
    display: block;
  }
}
</style>
